<template>


    <el-button type="primary"  @click="handleAdd">
       新增比赛视频信息
      </el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column label="视频名称" prop="videoName" />
        <el-table-column label="视频比赛" prop="title"  />
        <el-table-column label="比赛赛程" prop="courseName"  />
        <el-table-column label="视频类型" prop="videoType" :formatter="idFormatter" />
        <el-table-column label="封面" prop="videoConverPath" >
          <template width="90" #default="scope">
          <img style="width:80px;height:80px;border:none;" :src="getServerUrl()+'/'+scope.row.videoConverPath">
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column align="right">
          <template #header>
        <el-input v-model="queryForm.query"  @input="initUserList" placeholder="请输入内容"></el-input>
          </template>
          <template #default="scope">
            <el-button size="small"  type="primary" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="deleteVideo( scope.row.id)" >
             删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :size="size"
          background layout="prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
    
        <el-dialog v-model="dialogFormVisible" title="新增比赛视频" width="800" z-index="500">

  <el-form :model="videoFrom" :rules="rules" ref="videoFromRef" label-width="auto" style="max-width: 600px">
   
   <el-form-item prop="videoName" label="视频名称">
     <el-input v-model="videoFrom.videoName" placeholder="请输入视频名称"></el-input>
   </el-form-item>
   <el-form-item prop="contestId" label="选择比赛">

     <el-select 
        v-model="videoFrom.contestId"
        filterable
        remote
        :remote-method="remoteMethod"
        :loading="loading"
        @change="getCourse"
         placeholder="选择比赛">
         <el-option
          v-for="item in contestOptions"
          :key="item.id"
          :label="item.contestTitle"
          :value="item.id"
        />
      </el-select>



   </el-form-item>
   <el-form-item prop="courseId" label="选择赛程">

     <el-select
      v-model="videoFrom.courseId"
      placeholder="Select"
      size="large"
      style="width: 240px"
    >
      <el-option
        v-for="item in courseOptions"
        :key="item.id"
        :label="item.courseName"
        :value="item.id"
      />
    </el-select>
   </el-form-item>

   <el-form-item prop="videoType" label="选择类别">
     <el-select
      v-model="videoFrom.videoType"
      placeholder="Select"
      size="large"
      style="width: 240px"
    >
      <el-option
        v-for="item in videoTypeList"
        :key="item.dictValue"
        :label="item.dictLabel"
        :value="item.dictValue"
      />
    </el-select>


   </el-form-item>

   <el-form-item prop="videoConverPath" label="视频封面">
    <el-input disabled v-model="videoFrom.videoConverPath" placeholder="请输入视频封面"></el-input>
    <el-upload
    class="avatar-uploader"
    :action="getServerUrl()+'/video/uploadInco'"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
   </el-form-item>


   <el-form-item prop="videoConverPath" label="比赛视频">
    <el-input disabled v-model="videoFrom.videoPath" placeholder="上传视频"></el-input>
    <el-upload
    class="avatar-uploader"
    :action="getServerUrl()+'/video/uploadVideo'"
    :show-file-list="false"
    :before-upload="beforeUpload"
    :on-success="handleVideoSuccess">
    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>

  <vue3VideoPlay 
    v-if="videoFrom.videoPath"
      width="800px"
      :title="videoFrom.videoName"
      :src="getServerUrl()+'/'+videoFrom.videoPath"
      :poster="getServerUrl()+'/'+videoFrom.videoConverPath"
      @play="onPlay"
      @pause="onPause" 
      @timeupdate="onTimeupdate" 
      @canplay="onCanplay" />

   </el-form-item>

 </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click=" submitForm()">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
      <div v-if="isUploading" class="mask">
      <div  >视频上传中...</div>
    </div>
    </template>
    
    <script  setup>
         import {ref,reactive} from 'vue';
         import request ,{getServerUrl} from '@/util/request';
         import { ElMessage ,ElMessageBox } from 'element-plus'
         import { Plus } from '@element-plus/icons-vue'
         const isUploading=ref(false);
         const dialogFormVisible = ref(false)
         const tableData=ref([]);
         const videoTypeList=ref([]);
         const contestOptions = ref([])
         const courseOptions=ref([])
         const loading = ref(false)
        
         const total=ref(0);
         const queryForm=ref({
            param:{
              query:'',
              videoType:'',
              contestId:'',
              courseId:''
            },
            pageNum:1,
            pageSize:10
         })
         const initUserList=async ()=>{
           const res= await request.post("/video/list",queryForm.value)
           tableData.value=res.data.data.dataList;
           total.value=res.data.data.total;
         }
         initUserList();
         const inivideoTypeList=async ()=>{
           const res= await request.get("dict/getListByType/contest_type")
           videoTypeList.value=res.data.data;
           
         }

  const idFormatter=(row, column)=>{
    var value = "";
    for (var i = 0; i < videoTypeList.value.length; i++){
        var item = videoTypeList.value[i];
        if (row.videoType == item.dictValue) {
          value = item.dictLabel;
          break;
        }
      }
      return value;
  }
  const deleteVideo=(id)=>{
  
  ElMessageBox.confirm(
          '确认删除',
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
      ).then(() => {
          request.get("video/"+id).then(res=>{
            if(res.data.code==200){
              initUserList()
              ElMessage.success("删除成功")
            }else{
              ElMessage.error(res.data.msg);
            }
          })
    })}


         inivideoTypeList();

         const handleSizeChange=(pageSize)=>{
            queryForm.value.pageNum=1;
            queryForm.value.pageSize=pageSize
            initUserList();
         }
         const handleCurrentChange=(pageNum)=>{
            queryForm.value.pageNum=pageNum;
            initUserList();
         }
     
         const videoFrom = reactive({
          id:'',
          contestId:'',
          courseId:'',
          videoType:'',
          videoName:'',
          videoPath:'',
          videoConverPath:''
    })
    const resstvideoFrom = reactive({
          id:'',
          contestId:'',
          courseId:'',
          videoType:'',
          videoName:'',
          videoPath:'',
          videoConverPath:''
    })
    const imageUrl=ref("")
    const videoFromRef = ref(null);
    const rules = {
      contestId: [
        { required: true, message: '请选择赛事', trigger: 'blur' }
      ],
      courseId: [
        { required: true, message: '请选择赛程', trigger: 'blur' }
      ],
      videoType: [
        { required: true, message: '请选择类型', trigger: 'blur' }
      ],
      videoName: [
        { required: true, message: '请输入比赛名称', trigger: 'blur' }
      ],
      videoPath: [
        { required: true, message: '请上传视频', trigger: 'blur' }
      ],
      videoConverPath: [
        { required: true, message: '请上传视频封面', trigger: 'blur' }
      ]
    };
     
    const submitForm = () => {
      videoFromRef.value.validate((valid) => {
        if (valid) {
          request.post("video/saveOrUpdate",videoFrom).then(res=>{
           if(res.data.code==200){
            initUserList();
            resetForm();
            ElMessage.success("新增成功")
           }else{
            ElMessage.error(res.data.msg);
           }
          })
        } else {
          return false;
        }
      });
    };
    const handleEdit=(index,row)=>{
     let obj=  Object.assign({}, row)
     videoFrom.id=obj.id;
     videoFrom.contestId=obj.contestId;
     videoFrom.courseId=obj.courseId;
     videoFrom.videoType=obj.videoType;
     videoFrom.videoName=obj.videoName;
     videoFrom.videoPath=obj.videoPath;
     videoFrom.videoConverPath=obj.videoConverPath;
     imageUrl.value= getServerUrl()+'/'+obj.videoConverPath;
     getContestById(obj.contestId);
     getCourseById(obj.courseId);
    dialogFormVisible.value = true
    }
    
    const handleAdd=()=>{
    
      dialogFormVisible.value = true
    }
    
    const resetForm = () => {
      videoFrom.id='';
     videoFrom.contestId='';
     videoFrom.courseId='';
     videoFrom.videoType='';
     videoFrom.videoName='';
     videoFrom.videoPath='';
     videoFrom.videoConverPath='';
     imageUrl.value= '';
     
          dialogFormVisible.value = false
        }

const handleAvatarSuccess= (res)=>{
  imageUrl.value= getServerUrl()+'/'+res.data.src
  videoFrom.videoConverPath=res.data.src;
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2M!')
  }
  return isJPG && isLt2M
}

const remoteMethod = (param) => {
            if (param) {
                loading.value = true
                setTimeout(() => {
                loading.value = false
                request.get("contest/getContestByName/"+param).then(res=>{
                    if(res.data.code==200){
                      contestOptions.value  =res.data.data
                    }else{
                      contestOptions.value = []
                    }
                    })
                
                }, 200)
            } else {
              contestOptions.value = []
            }
        }

        const getContestById = (param) => {
            if (param) {
                loading.value = true
                setTimeout(() => {
                loading.value = false
                request.get("contest/getById/"+param).then(res=>{
                    if(res.data.code==200){
                      contestOptions.value  =res.data.data
                    }else{
                      contestOptions.value = []
                    }
                    })
                
                }, 200)
            } else {
              contestOptions.value = []
            }
        }

const getCourse = async (value)=>{
  const res= await request.post("/course/list", {
            query:value,
            pageNum:1,
            pageSize:100
         })
  courseOptions.value=res.data.data.dataList;
}
const getCourseById = async (value)=>{
  const res= await request.get("/course/getById/"+value)
  courseOptions.value=res.data.data;
  
}


 
const beforeUpload=(file)=>{
  
  isUploading.value=true;
 
         
    }
const handleVideoSuccess=(res)=>{
 
   if(res.code==0){
    ElMessage.success("视频上传成功");
    videoFrom.videoPath=res.data.src;
    isUploading.value=false;
   }
   
}


const onPlay = (ev) => {
  console.log('播放')
}
const onPause = (ev) => {
  console.log(ev, '暂停')
}

const onTimeupdate = (ev) => {
  console.log(ev, '时间更新')
}
const onCanplay = (ev) => {
  console.log(ev, '可以播放')
}
 


</script>
    
    <style lang="scss" scoped>
    .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000; 
}
    </style>
    